const express = require('express');
const router = express.Router();
const { createUser, findUserByUsername, verifyPassword } = require('../models/userModel');
const { generateToken } = require('../middleware/auth');

// 用户注册
router.post('/register', async (req, res) => {
    try {
        const userId = await createUser(req.body);
        res.status(201).json({ message: '注册成功', userId });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 用户登录
router.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;
        const user = await findUserByUsername(username);
        
        if (!user) {
            throw new Error('用户名或密码错误');
        }

        const isValid = await verifyPassword(password, user.password);
        if (!isValid) {
            throw new Error('用户名或密码错误');
        }

        const token = generateToken(user);
        res.json({ token, user: { id: user.id, username: user.username, role: user.role } });
    } catch (error) {
        res.status(401).json({ error: error.message });
    }
});

module.exports = router; 